<template>
  <div class="content">
    <el-form ref="addRef" :model="projectForm" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="10">
          <el-form-item label="状态：" prop="qaStatus">
            <el-select v-model="projectForm.qaStatus" placeholder="请选择" clearable>
              <el-option
                v-for="category in qustionDictData"
                :key="category.dictValue"
                :label="category.dictLabel"
                :value="category.dictValue"
                :disabled="category.disabled" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="类型：" prop="qaType">
            <el-select v-model="projectForm.qaType" placeholder="请选择" clearable>
              <el-option
                v-for="category in dict.dictMap['task_question_type']"
                :key="category.dictValue"
                :label="category.dictLabel"
                :value="category.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="主题：" prop="qaTitle">
        <el-input v-model="projectForm.qaTitle" :disabled="source === 'detail'" placeholder="请输入" />
      </el-form-item>
      <el-form-item label="详细：" prop="qaDetail">
        <Editor
          ref="editor"
          :valueHtml="projectForm.qaDetail"
          :folderId="folderParentId"
          :folderName="'QA'"
          :folderType="'QA'"
          :height="'200px'"
          @fullScreenFlag="
            (val) => {
              emit('changeFullScreen', val)
            }
          " />
      </el-form-item>
      <el-row>
        <el-col :span="10">
          <el-form-item label="优先级：" prop="qaPriority">
            <el-select v-model="projectForm.qaPriority" placeholder="请选择" clearable>
              <el-option
                v-for="category in dict.dictMap['task_priority']"
                :key="category.dictValue"
                :label="category.dictLabel"
                :value="category.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="预计工时：" prop="planCostHour">
            <el-input-number
              style="width: 100%"
              :min="0"
              :max="Number(dict.dictMap['work_time'][4]['dictValue'])"
              v-model="projectForm.planCostHour"
              placeholder="请输入"
              :controls="false" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="10">
          <el-form-item label="程度：" prop="qaLevel">
            <el-select v-model="projectForm.qaLevel" placeholder="请选择" clearable>
              <el-option
                v-for="category in dict.dictMap['task_question_leave']"
                :key="category.dictValue"
                :label="category.dictLabel"
                :value="category.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="计划时间：" prop="planDates">
            <!-- :model-value="[projectForm.planStart, projectForm.planEnd]" -->
            <el-date-picker
              v-model="projectForm.planDates"
              type="daterange"
              :unlink-panels="true"
              format="YYYY-MM-DD"
              date-format="YYYY-MM-DD"
              @update:model-value="planDateChange" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="关联问题：">
        <el-select
          v-model="projectForm.connectQA"
          @change="changeConnectTask"
          multiple
          clearable
          placeholder="关联问题"
          style="width: 100%">
          <el-option
            v-for="item in conectTaskList"
            :key="item.taskId"
            :label="'#' + item.taskTitle"
            :value="item.taskId" />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="7">
          <el-form-item label="指派给：" prop="executeUser">
            <SelectUser
              :userList="projectMemberList"
              :defaultSelectUserList="defaultUserIdList"
              @select="getExecute"></SelectUser>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="跟踪者：" prop="trackUser">
            <SelectUser
              :userList="projectMemberList"
              :defaultSelectUserList="defaultFollowUserIdList"
              @select="getTrack"></SelectUser>
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item label="测试人：" prop="testUser">
            <SelectUser
              :userList="projectMemberList"
              :defaultSelectUserList="defaultTestUserIdList"
              only
              @select="getTest"></SelectUser>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item class="customize">
        <template #label>
          <span>附件：</span>
          <el-tooltip placement="top">
            <el-icon>
              <QuestionFilled />
            </el-icon>
            <template #content>
              <div v-html="uploadTip"></div>
            </template>
          </el-tooltip>
        </template>
        <el-upload
          :file-list="myFileList"
          class="upload-demo"
          action=""
          :accept="uploadAccept()"
          multiple
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :on-change="onChange"
          :auto-upload="false">
          <el-button>点击上传</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="我的任务：">
        <el-select v-model="projectForm.taskId" placeholder="请选择" clearable style="width: 100%">
          <el-option v-for="task in myTaskList" :key="task.taskId" :label="'#' + task.taskTitle" :value="task.taskId" />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { QuestionFilled } from '@element-plus/icons-vue'
import { useDictionary } from '@/use/use-dictionary'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getTcTaskInfoList } from '@/assets/api/task'
import { addQaInfo, editTcQaInfo, getProjectFolderId } from '@/assets/api/quality'
import { uploadFile } from '@/assets/api/document'
import Editor from '@/components/Editor.vue'
import { uploadAccept } from '@/utils/task-utils'

const props = defineProps({
  modelValue: Boolean,
  projectId: String,
  ifAdd: Boolean, //是新增还是编辑
  editData: Object, //编辑的回显数据
  projectMemberList: Array, // 获取项目成员
  source: String, //来源 详情或者新增
  addHandleStatus: Number, //新增 状态值判断
})
const emit = defineEmits(['update:modelValue', 'refresh', 'changeFullScreen', 'changeLoading'])
defineExpose({ submitFunc })

const dict = useDictionary([
  'task_question_status',
  'task_question_type',
  'task_priority',
  'task_question_leave',
  'work_time',
])
let qustionDictList = ref([])
let qustionDictData = ref([])
qustionDictList.value = dict.dictMap['task_question_status']

qustionDictData.value = qustionDictList.value.map((e) => {
  let obj = {
    ...e,
  }
  if (props.addHandleStatus === parseInt(e.dictValue)) {
    obj.disabled = false
  } else {
    obj.disabled = props.ifAdd ? true : false
  }
  return obj
})

const myFileList = ref([])

onMounted(() => {
  // getTcTaskInfoData('task') //查询我的任务
  getTcTaskInfoData()
  if (!props.ifAdd) {
    //编辑
    projectForm.value = {
      ...props.editData,
      qaStatus: props.editData.qaStatus + '',
      qaType: props.editData.qaType + '',
      qaPriority: props.editData.qaPriority + '',
      qaLevel: props.editData.qaLevel + '',
      connectQA: props.editData.tcTaskInfos.map((obj) => obj.taskId),
      planDates: [props.editData.planStart, props.editData.planEnd],
    }
    defaultUserIdList.value = getDefaultUseList(1)
    defaultFollowUserIdList.value = getDefaultUseList(2)
    defaultTestUserIdList.value = getDefaultUseList(3)
    if (Array.isArray(props.editData.taskAttach)) {
      myFileList.value = JSON.parse(props.editData.taskAttach).map((obj) => {
        return {
          ...obj,
          name: obj.resourceName,
        }
      })
    }
  } else {
    initData()
  }
})

// function changeContent(editorChildre, htmlCont) {
//   console.error(editorChildre, htmlCont)
// }
function getDefaultUseList(code) {
  return props.editData.tcQaMembers
    ?.filter((obj) => obj.userTypeCode === code)
    ?.map((item) => {
      return {
        userId: item.taskUserId,
        userName: item.taskUserName,
      }
    })
}

const rules = reactive({
  qaStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
  qaType: [{ required: true, message: '请选择类型', trigger: 'change' }],
  qaTitle: [
    { required: true, message: '请填写主题', trigger: 'blur' },
    { max: 15, message: '字数不能超过15', trigger: 'blur' },
  ],
  qaDetail: [{ required: true, message: '请填写详细', trigger: 'blur' }],
  qaPriority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  planCostHour: [{ required: true, message: '请填写预计工时', trigger: 'blur' }],
  qaLevel: [{ required: true, message: '请选择程度', trigger: 'change' }],
  planDates: [
    {
      type: 'array',
      required: true,
      message: '请选择计划日期区间',
      fields: {
        // tpye类型试情况而定,所以如果返回的是date就改成date,如果返回的是string就改成string
        0: { type: 'date', required: true, message: '请选择开始日期' },
        1: { type: 'date', required: true, message: '请选择结束日期' },
      },
    },
  ],
  connectQA: [{ type: 'array', required: true, message: '请选择关联问题', trigger: 'change' }],
  executeUser: [{ type: 'array', required: true, message: '请选择指派给', trigger: 'change' }],
  trackUser: [{ type: 'array', required: true, message: '请选择跟踪者', trigger: 'change' }],
  testUser: [{ type: 'array', required: true, message: '请选择测试人', trigger: 'change' }],
  taskId: [{ required: true, message: '请选择我的任务', trigger: 'change' }],
})
let projectForm = ref({
  planStart: '',
  planEnd: '',
  connectQA: [],
  executeUser: [],
  trackUser: [],
  testUser: [],
  planDates: [],
})
function planDateChange(date) {
  if (date) {
    projectForm.value.planStart = dayjs(date[0]).format('YYYY-MM-DD')
    projectForm.value.planEnd = dayjs(date[1]).format('YYYY-MM-DD')
  } else {
    projectForm.value.planStart = ''
    projectForm.value.planEnd = ''
  }
}

function initData() {
  projectForm.value = {}
  projectForm.value.qaDetail = '<p></p>'
  projectForm.value.connectQA = []
  defaultUserIdList.value = [] //默认/回显--指派给
  defaultFollowUserIdList.value = [] //默认/回显--跟踪者
  defaultTestUserIdList.value = [] //默认/回显--测试者'
  addRef.value.resetFields()
}
const editor = ref(null)
function getExecute(val) {
  projectForm.value.executeUser = val
}
function getTrack(val) {
  projectForm.value.trackUser = val
}
function getTest(val) {
  projectForm.value.testUser = val
  if (Array.isArray(val) && val.length) {
    getTcTaskInfoData('task', val[0]['userId'])
  } else {
    myTaskList.value = []
    projectForm.value.taskId = null
  }
}
function formatMember(userList, code) {
  //数据格式组装
  //code 1执行 2监督 3测试
  return userList.map((obj) => {
    return {
      userTypeCode: code,
      taskUserId: obj.userId,
    }
  })
}
const submit = () => {
  // 获取富文本框内容
  projectForm.value.tcQaMembers = [
    ...formatMember(projectForm.value.executeUser, 1),
    ...formatMember(projectForm.value.trackUser, 2),
    ...formatMember(projectForm.value.testUser, 3),
  ]
  projectForm.value.projectId = props.projectId
  projectForm.value.tcTaskInfos = projectForm.value.connectQA.map((id) => {
    return {
      taskId: id,
    }
  })
  let submitName = props.ifAdd ? addQaInfo : editTcQaInfo
  submitName(projectForm.value).then((res) => {
    if (res.code === 200) {
      ElMessage.success('提交成功')
      emit('refresh')
      initData()
    } else {
      ElMessage.error(res.msg)
    }
    emit('changeLoading', false)
  })
}

const myTaskList = ref([])
const conectTaskList = ref([])
function getTcTaskInfoData(str = '', userId) {
  let params
  if (str === 'task') {
    //查询我的任务
    params = { projectId: props.projectId, taskUserId: userId, currentStatus: 2 }
  } else {
    //查询任务关联
    params = { projectId: props.projectId, currentStatus: 4 }
  }
  getTcTaskInfoList(params).then((res) => {
    if (res.code === 200) {
      if (str === 'task') {
        myTaskList.value = res.rows || []
      } else {
        conectTaskList.value = res.rows || []
      }
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const selectConnectTask = ref([])
const defaultUserIdList = ref([]) //默认/回显--指派给
const defaultFollowUserIdList = ref([]) //默认/回显--跟踪者
const defaultTestUserIdList = ref([]) //默认/回显--测试者
function changeConnectTask(e) {
  //改变关联问题/任务
  selectConnectTask.value = []
  conectTaskList.value.forEach((task) => {
    e.forEach((taskId) => {
      if (taskId === task.taskId) {
        selectConnectTask.value.push(task)
      }
    })
  })
  defaultUserIdList.value = selectConnectTask.value.map((obj) => {
    return {
      userId: obj.taskUserId,
      userName: obj.taskUserName,
    }
  })
}

const folderParentId = ref('')
// 上传文件之前的钩子
function beforeUpload(file) {
  getProjectFolderId(props.projectId).then((res) => {
    folderParentId.value = res.data
  })
}
getFolderParentId()

function getFolderParentId() {
  getProjectFolderId(props.projectId).then((res) => {
    if (res.code === 200) {
      folderParentId.value = res.data
    } else {
      //
    }
  })
}

function handleUploadFile() {
  return new Promise((resolve, reject) => {
    const formData = new FormData()
    formData.append('folderParentId', folderParentId.value)
    formData.append('relativePath', '问题')
    formData.append('type', 'qa')
    myFileList.value.forEach((file) => {
      if (!file.resourceId) {
        //只上传带uid的，带uid的是刚上传的，不带的是已经上传服务器编辑带过来的
        formData.append('files', file)
      }
    })
    //是否有需要新上传的
    let flag = myFileList.value.find((obj) => !obj.resourceId)
    if (flag) {
      uploadFile(formData).then((res) => {
        if (res.code === 200) {
          resolve(res)
        } else {
          reject(res)
        }
      })
    } else {
      //没有新上传的 就传个空
      resolve({ data: [] })
    }
  })
}

// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
function onChange(file) {
  myFileList.value.push(file.raw)
}

// 文件列表移除文件时的钩子
function handleRemove(file) {
  if (!file.resourceId) {
    //新增的
    myFileList.value = myFileList.value.filter((obj) => obj.uid !== file.raw.uid)
  } else {
    //已经传到服务器上的
    myFileList.value = myFileList.value.filter((obj) => obj.resourceId !== file.resourceId)
  }
}
const addRef = ref()
function submitFunc() {
  projectForm.value.qaDetail = editor.value.getHtml()

  addRef.value.validate((valid) => {
    if (valid) {
      if (projectForm.value.qaDetail === '<p><br></p>') {
        ElMessage.warning('请填写详细')
        return false
      }
      emit('changeLoading', true)
      //保存
      if (myFileList.value.length) {
        //如果有附件 先上传附件(因为想把上传放在确定上传删删改改之后再上传服务器)
        handleUploadFile() //先批量上传附件
          .then((res) => {
            //附件列表筛选出还剩下的存在服务器上的+现在刚传的
            let attachArr = [...myFileList.value.filter((obj) => obj.resourceId), ...res.data]
            projectForm.value.taskAttach = JSON.stringify(attachArr)
            submit()
          })
          .catch((err) => {
            ElMessage.warning(err.msg)
            emit('changeLoading', false)
          })
      } else {
        submit()
      }
    }
  })
}

const uploadTip = ref('只能上传jpg/png/jpeg/pdf/doc/docx/xls/xlsx/mp4/avi文件')
</script>

<style scoped lang="scss">
.customize {
  :deep(.elp-form-item__label) {
    display: flex;
    align-items: center;
  }
}
</style>
